package com.briup.day23;

/**
 * @author ThinkBook
 */
public class Test03_ThreadGroup {
    public static void main(String[] args) throws InterruptedException {
        ThreadGroup myGroup = new ThreadGroup("自定义线程组");
        Runnable target = new Runnable() {
            @Override
            public void run() {
                String name = Thread.currentThread().getName();
                System.out.println("in " + name + " run ...");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(name + " run end.");
            }
        };

        Thread th1 = new Thread(myGroup,target,"th1");
        Thread th2 = new Thread(myGroup,target,"th2");
        Thread th3 = new Thread(myGroup,target,"th3");

        th1.start();
        th2.start();
        th3.start();

        int size = myGroup.activeCount();
        System.out.println("myGroup活动的线程数量: " + size);
        System.out.println("myGroup是否销毁: " + myGroup.isDestroyed());

        //创建线程数组，存储 线程组所有的线程
        Thread[] arr = new Thread[size];
        myGroup.enumerate(arr);

        System.out.println("遍历线程组活动的所有线程: ");
        for(Thread t : arr) {
            System.out.println(t);
        }

        Thread.sleep(6000);
        //线程组所有子线程 已经全部run运行结束，子线程销毁
        size = myGroup.activeCount();
        System.out.println("6s后，myGroup活动的线程数量: " + size);  //0

        //销毁线程组(注意：如果线程组还有尚未运行结束的线程，则抛出异常；如果都已经结束，则可以直接销毁)
        myGroup.destroy();
        System.out.println("销毁线程 ");
        System.out.println("6s以后，myGroup是否销毁: " + myGroup.isDestroyed());   //true
    }
}
